import logging

import yaml
from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException


class BasePage:
    def __init__(self, driver: WebDriver = None):
        self.driver = driver

    # 查找元素并点击
    def find_and_click(self, by, locator=None):
        self.log_info("find_and_click:")
        self.log_info(by)
        self.log_info(locator)
        if locator is None:
            ele = self.driver.find_element(*by)
        else:
            ele = self.driver.find_element(by=by, value=locator)
        return ele.click()

    # 查找元素
    def find(self,by,locator=None):
        self.log_info("find:")
        self.log_info(by)
        self.log_info(locator)
        if locator is None:
            ele = self.driver.find_element(*by)
        else:
            ele = self.driver.find_element(by=by,value=locator)
        return ele

    # 查找元素并输入内容
    def find_and_send(self, by, locator, keys):
        self.log_info("find_and_send:")
        self.log_info(by)
        self.log_info(locator)
        self.log_info(keys)
        return self.driver.find_element(by=by, value=locator).send_keys(keys)

    # 滑动查找元素
    def swipe_find(self, num, text):
        self.log_info("swipe_find:")
        self.log_info(num)
        self.log_info(text)
        for i in range(num):
            try:
                ele = self.driver.find_element(MobileBy.XPATH, f"//*[@text='{text}']")
            except:
                size = self.driver.get_window_size()
                width = size['width']
                height = size['height']
                start_x = width / 2
                start_y = height * 0.8
                end_x = width / 2
                end_y = height * 0.4
                self.driver.swipe(start_x, start_y, end_x, end_y)
                ele = self.driver.find_element(MobileBy.XPATH, f"//*[@text='{text}']")
            if i == num - 1:
                raise NoSuchElementException(f"找了{num}次，未找到元素")
            return ele

    # 返回操作
    def back_action(self, num):
        self.log_info("back:")
        self.log_info(num)
        for i in range(num):
            self.driver.back()

    # 获取toast消息
    def get_toast_message(self):
        self.log_info("toast:")
        return self.driver.find_element(MobileBy.XPATH,"//*[@class='android.widget.Toast']").get_attribute("text")

    # 获取当前页面元素
    def get_page_source(self):
        self.log_info("get_page_source")
        return self.driver.page_source

    # 日志打印
    def log_info(self,message):
        logging.info(message)